import { UploadOutlined } from '@ant-design/icons';
import { useState } from 'react';
import { Button, message, Space, Cascader, Checkbox, DatePicker, Form, Input, InputNumber, Radio, Select, Slider, Switch, TreeSelect, Upload, Rate } from 'antd';
import type { UploadFile, RcFile } from 'antd/es/upload/interface';

// import axios from 'axios'

const { RangePicker } = DatePicker;
const { TextArea } = Input;

function dealFormData(values: any, fileList: any) {
  const formData = new FormData();
  values.name ? formData.append('name', values.name) : "";
  values.eventRangePicker ? formData.append('dsl_start_time', values.eventRangePicker[0].valueOf()) : null;
  values.vulnerabilityRangePicker ? formData.append('vuln_sql_end_time', values.vulnerabilityRangePicker[1].valueOf()) : null;
  fileList.forEach((file: any) => {
    formData.append('file', file as RcFile);
  });
  return formData;
}

export default function BaseForm() {
  // 定义表单对象
  const [form] = Form.useForm();
  // 设置表单默认可填写状态
  const [componentDisabled, setComponentDisabled] = useState<boolean>(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [fileCheck, setFileCheck] = useState<boolean>(false);

  // 表单提交
  const onFinish = (values: any) => {
    console.log(values);
    fileUp(values);
  };

  // 表单重置
  const onReset = () => {
    form.resetFields();
  };

  // 表单默认填充
  const onFill = () => {
    form.setFieldsValue({
      name: '默认填充数据',
      select: "demo",
      file: [
        { name: "JavaScript学习指南.pdf", }
      ]
    });
  };

  // 上传附件校验函数
  const beforeUpload = (file: any) => {
    setFileList([...fileList, file]);
    // Validate file type and size
    const allowedTypes = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'];
    const isAllowedType = allowedTypes.includes(file.type);
    if (!isAllowedType) {
      message.error('只能上传 PDF, DOCX, 或者 DOC 类型的文件!');
    }
    const isSizeValid = file.size <= 5 * 1024 * 1024; // 5MB
    if (!isSizeValid) {
      message.error('File size must be within 5MB!');
    }
    // return isAllowedType && isSizeValid;
    if (isAllowedType && isSizeValid) {
      setFileCheck(true);
    }
    return false;
  };

  // 文件上传网络请求
  const fileUp = (values: any) => {
    let msg = "工单创建成功！";
    // 创建FormData对象将表单收集的数据处理
    const resFormData = dealFormData(values, fileList);
    const url = "/judgeOperation/v1/ticket/update_ticket";
    let id;
    // 如果有啥特殊条件可以往表单对象添加
    if (id) {
      resFormData.append('id', id);
      msg = "工单更新成功！";
    }
    const headers = {
      'tenantId': "ISOP#@!STARTNULLISOP#@!END",
    }
    // 上传文件存在而且符合文件上传文件后缀要求才允许下一步，否则提示后结束函数
    if (fileList.length > 0 && !fileCheck) {
      message.error('文件上传不符合规范!');
      return;
    }
    // 进行网络请求
    // axios.post(url, resFormData, { headers }).then((res: any) => {
    //   console.log(res);
    //   if (res.data.status == 200) {
    //     message.success(msg);
    //     close();
    //   } else {
    //     message.error("操作失败！");
    //   }
    // }).catch((err:any) => { })
  }

  return (
    <div className='antd_base_form'>
      <h1>表单基本项使用</h1>
      <div className='content_text'>
        <p>
          基础使用包含
          Checkbox多选框、Radio单选框、input输入框、select下拉选择框、TreeSelect树选择框、
          Cascader级联选择框、DatePicker日期选择、RangePicker时间范围选择框、InputNumber数字输入框、TextArea文本域、
          Switch开关、Slider滑块、Rate评分、组合表单、Upload文件上传 使用。
        </p>
      </div>
      <button className='returnButton'><a href="/">点击返回主菜单</a></button>
      <Checkbox
        checked={componentDisabled}
        onChange={(e) => setComponentDisabled(e.target.checked)}
      >
        Form disabled
      </Checkbox>
      <Form
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 14 }}
        layout="horizontal"
        disabled={componentDisabled}
        style={{ maxWidth: 600 }}
        onFinish={onFinish}
        form={form}
      >
        <Form.Item label="Checkbox" name="checkbox" valuePropName="checked">
          <Checkbox>Checkbox</Checkbox>
        </Form.Item>
        <Form.Item label="Radio" name="radio">
          <Radio.Group>
            <Radio value="apple"> Apple </Radio>
            <Radio value="pear"> Pear </Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="Input"
          name="name"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="Select" name="select">
          <Select>
            <Select.Option value="demo">Demo</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="TreeSelect" name="treeSelect">
          <TreeSelect
            treeData={[
              { title: 'Light', value: 'light', children: [{ title: 'Bamboo', value: 'bamboo' }] },
            ]}
          />
        </Form.Item>
        <Form.Item label="Cascader" name="cascader">
          <Cascader
            options={[
              {
                value: 'zhejiang',
                label: 'Zhejiang',
                children: [
                  {
                    value: 'hangzhou',
                    label: 'Hangzhou',
                  },
                ],
              },
            ]}
          />
        </Form.Item>
        <Form.Item label="DatePicker" name="DatePicker">
          <DatePicker />
        </Form.Item>
        <Form.Item label="RangePicker" name="RangePicker">
          <RangePicker />
        </Form.Item>
        <Form.Item label="InputNumber" name="InputNumber">
          <InputNumber />
        </Form.Item>
        <Form.Item label="TextArea" name="TextArea">
          <TextArea rows={4} />
        </Form.Item>
        <Form.Item label="Switch" valuePropName="checked" name="Switch">
          <Switch />
        </Form.Item>
        <Form.Item label="Slider" name="Slider">
          <Slider />
        </Form.Item>
        <Form.Item label="Rate" name="Rate">
          <Rate />
        </Form.Item>
        <Form.Item
          name="file"
          label={<span><b>附件</b></span>}
          valuePropName="fileList"
          getValueFromEvent={(e) => e.fileList.slice(-1)}
        // rules={[{ required: true, message: 'Please upload a file!' }]}
        >
          <Upload beforeUpload={beforeUpload} maxCount={1}>
            <Button icon={<UploadOutlined />}>Select File</Button>
          </Upload>
        </Form.Item>
        <Form.Item label="组合表单项">
          <Space.Compact>
            <Form.Item
              name={['address', 'province']}
              noStyle
              // rules={[{ required: true, message: 'Province is required' }]}
            >
              <Select placeholder="Select province">
                  <Select.Option value="hubei">湖北</Select.Option>
                  <Select.Option value="henan">河南</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              name={['address', 'street']}
              noStyle
              // rules={[{ required: true, message: 'Street is required' }]}
            >
              <Input style={{ width: '50%' }} placeholder="Input street" />
            </Form.Item>
          </Space.Compact>
        </Form.Item>
        <Form.Item>
          <Button className='button_form' type="primary" htmlType="submit">
            Submit
          </Button>
          <Button className='button_form' htmlType="button" onClick={onReset}>
            Reset
          </Button>
          <Button className='button_form' type="dashed" htmlType="button" onClick={onFill}>
            Fill form
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
